package com.chaihu.front.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaihu.bean.enums.MsgCode;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.base.constants.CommonConstant;
import com.chaihu.core.base.controller.SuperController;
import com.chaihu.core.context.IPageData;
import com.chaihu.utils.exception.BaseException;
import com.chaihu.utils.factory.ApplicationContextFactory;
import com.chaihu.utils.util.Assert;
import com.chaihu.utils.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 组件调用处理类
 */
@Slf4j
@RestController
public class CallComponentController extends SuperController {

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 前台调用api方法
     * /callComponent/activities.listActivitiess
     *
     * @return
     */

    @RequestMapping(path = "/callComponent/{api}")
    public ResponseEntity<String> callApi(
            @PathVariable String api,
            //@RequestBody String info,
            HttpServletRequest request) {
        ResponseEntity<String> responseEntity = null;
        String componentCode = "api";
        String componentMethod = "callApi";
        Map<String, Object> headers = new HashMap<String, Object>();
        IPageData pd = null;
        try {
            Assert.hasLength(api, "参数错误，未传入api编码");

            pd = (IPageData) request.getAttribute(CommonConstant.CONTEXT_PAGE_DATA);
            pd.setApiUrl("/api/" + api);
            //权限校验
//            hasPrivilege(restTemplate, pd, "/" + api);

            Object componentInstance = ApplicationContextFactory.getBean(componentCode);

            Assert.notNull(componentInstance, "未找到组件对应的处理类，请确认 " + componentCode);

            Method cMethod = componentInstance.getClass().getDeclaredMethod(componentMethod, IPageData.class);

            Assert.notNull(cMethod, "未找到组件对应处理类的方法，请确认 " + componentCode + "方法：" + componentMethod);

            log.debug("组件编码{}，组件方法{}，pd 为{}", componentCode, componentMethod, pd.toString());

            initHeadParam(request, headers);

            initUrlParam(request, headers);

            responseEntity = (ResponseEntity<String>) cMethod.invoke(componentInstance, pd);

        } catch (BaseException e) {
            log.error("调用api异常", e);
            responseEntity = new ResponseEntity<String>(JSONObject.toJSONString(e.getResult()), HttpStatus.OK);
        } catch (Exception e) {
            log.error("调用api异常", e);
            String msg = "";
            if (e instanceof InvocationTargetException) {
                Throwable targetEx = ((InvocationTargetException) e).getTargetException();
                if (targetEx != null) {
                    msg = targetEx.getMessage();
                }
            } else {
                msg = e.getMessage();
            }
            ResponseResult result = new ResponseResult(MsgCode.ERROR.getCode(), msg);
            responseEntity = new ResponseEntity<String>(JSON.toJSONString(result), HttpStatus.OK);
        } finally {
            log.debug("api调用返回信息为{}", responseEntity);
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                return responseEntity;
            }
            return responseEntity;
        }
    }

    /**
     * 调用组件方法
     * @return
     */

    @RequestMapping(path = "/callComponent/{componentCode}/{componentMethod}")
    public ResponseEntity<String> callComponent(
            @PathVariable String componentCode,
            @PathVariable String componentMethod,
            //@RequestBody String info,
            HttpServletRequest request) {
        ResponseEntity<String> responseEntity = null;
        Map<String, Object> headers = new HashMap<String, Object>();
        IPageData pd = null;
        try {
            Assert.hasLength(componentCode, "参数错误，未传入组件编码");
            Assert.hasLength(componentMethod, "参数错误，未传入调用组件方法");

            pd = (IPageData) request.getAttribute(CommonConstant.CONTEXT_PAGE_DATA);
            //权限校验 TODO
//            hasPrivilege(restTemplate, pd, "/" + componentCode + "/" + componentMethod);

            Object componentInstance = ApplicationContextFactory.getBean(componentCode);

            Assert.notNull(componentInstance, "未找到组件对应的处理类，请确认 " + componentCode);

            Method cMethod = componentInstance.getClass().getDeclaredMethod(componentMethod, IPageData.class);

            Assert.notNull(cMethod, "未找到组件对应处理类的方法，请确认 " + componentCode + "方法：" + componentMethod);

            log.debug("组件编码{}，组件方法{}，pd 为{}", componentCode, componentMethod, pd.toString());

            initHeadParam(request, headers);

            initUrlParam(request, headers);

            responseEntity = (ResponseEntity<String>) cMethod.invoke(componentInstance, pd);

        } catch (BaseException e) {
            log.error("调用组件异常", e);
            responseEntity = new ResponseEntity<String>(JSONObject.toJSONString(e.getResult()), HttpStatus.OK);
        } catch (Exception e) {
            log.error("调用组件异常", e);
            String msg = "";
            if (e instanceof InvocationTargetException) {
                Throwable targetEx = ((InvocationTargetException) e).getTargetException();
                if (targetEx != null) {
                    msg = targetEx.getMessage();
                }
            } else {
                msg = e.getMessage();
            }
            ResponseResult result = new ResponseResult(MsgCode.ERROR.getCode(), msg);
            responseEntity = new ResponseEntity<String>(JSON.toJSONString(result), HttpStatus.OK);
        } finally {
            boolean ignoreLog = responseEntity.getBody() != null && responseEntity.getBody().startsWith("data:image");
            if (!ignoreLog) {
                log.debug("组件调用返回信息为{}", responseEntity);
            }else {
                log.debug("组件调用返回信息为{}", " image or file");
            }
        }
        return responseEntity;
    }
}
